home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / bin / screen-profiles < prev    next >
Encoding:
Text File  |  2009-04-08  |  15.5 KB  |  504 lines

  1. #! /usr/bin/env python
  2. #
  3. #    screen-profiles
  4. #    Copyright (C) 2008 Canonical Ltd.
  5. #
  6. #    Authors: Nick Barcet <nick.barcet@ubuntu.com>
  7. #             Dustin Kirkland <kirkland@canonical.com>
  8. #
  9. #    This program is free software: you can redistribute it and/or modify
  10. #    it under the terms of the GNU General Public License as published by
  11. #    the Free Software Foundation, version 3 of the License.
  12. #
  13. #    This program is distributed in the hope that it will be useful,
  14. #    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. #    GNU General Public License for more details.
  17. #
  18. #    You should have received a copy of the GNU General Public License
  19. #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  20.  
  21. # If you change any strings, please generate localization information with:
  22. #       ./debian/rules get-po
  23.  
  24.  
  25. import sys, os, os.path, time, string, commands, gettext
  26. from ConfigParser import SafeConfigParser
  27. from snack import *
  28.  
  29. HOME=os.getenv("HOME")
  30. SHARE='/usr/share/screen-profiles'
  31. DOC='/usr/share/doc/screen-profiles'
  32. DEF_ESC="A"
  33. RELOAD = "If you are using the default set of keybindings, press\n<F5><enter> to activate these changes.\n\nOtherwise, exit this screen session and start a new one."
  34.  
  35. gettext.bindtextdomain('screen-profiles', SHARE+'/po')
  36. gettext.textdomain('screen-profiles')
  37. _ = gettext.gettext
  38.  
  39. # Command presets for windows creation
  40. cmd=(   ("System activity", "top", "top"),
  41.         ("System log", "log", "watch -n 10 tail -n 5 /var/log/syslog /var/log/auth.log /var/log/dmesg"),
  42.         ("Disk and ram usage", "mem", 'watch -n 30 "df -h; echo ""; free -mt"'))
  43.  
  44.  
  45. def ioctl_GWINSZ(fd):                  #### TABULATION FUNCTIONS
  46.     try:                                ### Discover terminal width
  47.         import fcntl, termios, struct, os
  48.         cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
  49.     except:
  50.         return None
  51.     return cr
  52.  
  53. def terminal_size():                    ### decide on *some* terminal size
  54.     cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)  # try open fds
  55.     if not cr:                                                  # ...then ctty
  56.         try:
  57.             fd = os.open(os.ctermid(), os.O_RDONLY)
  58.             cr = ioctl_GWINSZ(fd)
  59.             os.close(fd)
  60.         except:
  61.             pass
  62.     if not cr:                            # env vars or finally defaults
  63.         try:
  64.             cr = (env['LINES'], env['COLUMNS'])
  65.         except:
  66.             cr = (25, 80)
  67.     return int(cr[1]-5), int(cr[0]-5)         # reverse rows, cols
  68.  
  69. def menu(screen, size, isInstalled):
  70.     if isInstalled:
  71.         installtext=_("Remove screen by default at login")
  72.     else:
  73.         installtext=_("Install screen by default at login")
  74.  
  75.  
  76.     li = Listbox(height = 8, width = 60, returnExit = 1)
  77.     li.append(_("Help"), 1)
  78.     li.append(_("Change screen profile"), 2)
  79.     li.append(_("Toggle status notifications"), 3)
  80.     li.append(_("Change keybinding set"), 4)
  81.     li.append(_("Change escape sequence"), 5)
  82.     li.append(_("Create new window(s)"), 6)
  83.     li.append(_("Manage default windows"), 7)
  84.     li.append(installtext, 8)
  85.     bb = ButtonBar(screen, ((_("Exit"), )), compact = 1)
  86.  
  87.     g = GridForm(screen, _(" Screen Profiles Configuration Menu"), 1, 2)
  88.     g.add(li, 0, 0, padding=(4,2,4,2))
  89.     g.add(bb, 0, 1, padding=(1,1,0,0))
  90.  
  91.     if bb.buttonPressed(g.runOnce()) == "exit":
  92.         return 0
  93.     else:
  94.         return li.current()
  95.  
  96. def messagebox(screen, width, height, title, text, \
  97.     scroll=0, \
  98.     buttons=((_("Okay"), "okay"),(_("Cancel"), "cancel")) ):
  99.  
  100.     t = Textbox(width, height, text, scroll=scroll )
  101.     bb = ButtonBar(screen, buttons, compact = 1)
  102.     g = GridForm(screen, title, 1, 2)
  103.     g.add(t, 0, 0, padding=(0,0,0,0))
  104.     g.add(bb, 0, 1, padding=(1,1,0,0))
  105.  
  106.     return bb.buttonPressed(g.runOnce())
  107.  
  108. def help(screen, size, config):
  109.     f=file(DOC+'/help.txt')
  110.     text=f.read()
  111.     f.close()
  112.  
  113.     text=text.replace("<esckey>", getesckey(), 1)
  114.  
  115.     t = Textbox(70, 14, text, scroll=0)
  116.     bb = ButtonBar(screen, ((_("Menu"), )), compact = 1)
  117.     g = GridForm(screen, _("Screen Profiles Help"), 1, 3)
  118.     g.add(t, 0, 0, padding=(0,0,0,0))
  119.     g.add(bb, 0, 2, padding=(1,1,0,0))
  120.  
  121.     button = bb.buttonPressed(g.runOnce())
  122.  
  123.     return 100
  124.  
  125. def profile(screen, size):
  126.     li = Listbox(height = 8, width = 60, scroll = 1, returnExit = 1)
  127.  
  128.     for choice in commands.getoutput('select-screen-profile -l').splitlines():
  129.         if choice == "ubuntu":
  130.             li.append(choice+("-light"), choice)
  131.         else:
  132.             li.append(choice, choice)
  133.  
  134.     bb = ButtonBar(screen, ((_("Apply"), "apply"), (_("Cancel"), "cancel")), compact = 1)
  135.  
  136.     g = GridForm(screen, _("Which profile would you like to use?"), 1, 2)
  137.     g.add(li, 0, 0, padding=(4,2,4,2))
  138.     g.add(bb, 0, 1, padding=(1,1,0,0))
  139.  
  140.     if bb.buttonPressed(g.runOnce()) != "cancel":
  141.         commands.getoutput('select-screen-profile --set %s' % li.current())
  142.         button = messagebox(screen, 60, 4, _("Message"), _(RELOAD), \
  143.             buttons=((_("Menu"), )))
  144.     return 100
  145.  
  146. def keybindings(screen, size):
  147.     li = Listbox(height = 6, width = 60, returnExit = 1)
  148.     for choice in commands.getoutput('ls '+SHARE+'/keybindings').splitlines():
  149.         li.append(choice, choice)
  150.     bb = ButtonBar(screen, ((_("Apply"), "apply"), (_("Cancel"), "cancel")), compact = 1)
  151.     g = GridForm(screen, _("Which set of keybindings would you like to use?"), 1, 2)
  152.     g.add(li, 0, 0, padding=(4,2,4,2))
  153.     g.add(bb, 0, 1, padding=(1,1,0,0))
  154.     if bb.buttonPressed(g.runOnce()) != "cancel":
  155.         switch_keybindings(li.current())
  156.         button = messagebox(screen, 60, 4, _("Message"), _(RELOAD), \
  157.             buttons=((_("Menu"), )))
  158.     return 100
  159.  
  160. def switch_keybindings(set):
  161.     commands.getoutput("sed -i -e 's:^source .*$:source "+SHARE+"/keybindings/"+set+":' "+HOME+"/.screen-profiles/keybindings")
  162.  
  163. def newwindow(screen, size):
  164.     title=Entry(8, text="bash", returnExit=1)
  165.     titlel=Label(_("Title: "))
  166.     command=Entry(20, text="/bin/bash", returnExit=1)
  167.     commandl=Label(_("Command: "))
  168.  
  169.     rl=Label(_("Presets: "))
  170.     if len(cmd) > 10:
  171.         scroll=1
  172.         size=10
  173.     else:
  174.         scroll=0
  175.         size = len(cmd)
  176.  
  177.     r=CheckboxTree(size, scroll=scroll)
  178.     count=0
  179.     for cur in cmd:
  180.         r.append(cur[0], count)
  181.         count=count+1
  182.  
  183.     cb=Checkbox(_("Add to default windows"))
  184.  
  185.     bb = ButtonBar(screen, ((_("Apply"), "apply"), (_("Cancel"), "cancel")), compact = 1)
  186.  
  187.     g = GridForm(screen, _("Create new window(s):"), 2, 5 )
  188.     g.add(titlel, 0, 0, anchorLeft=1,padding=(4,1,0,1))
  189.     g.add(title, 1, 0, anchorLeft=1)
  190.     g.add(commandl, 0, 1, anchorLeft=1, anchorTop=1,padding=(4,0,0,1))
  191.     g.add(command, 1, 1, anchorLeft=1)
  192.     g.add(rl, 0, 2, anchorLeft=1,padding=(4,0,0,1))
  193.     g.add(r, 1, 2)
  194.     g.add(cb, 1, 3, padding=(4,1,0,1))
  195.     g.add(bb, 1, 4, padding=(4,1,0,0))
  196.  
  197.     if bb.buttonPressed(g.runOnce()) != "cancel":
  198.         sel=r.getSelection()
  199.         if sel:
  200.             for s in sel:
  201.                 win='screen -t %s %s' % (cmd[s][1], cmd[s][2])
  202.                 commands.getoutput(win)
  203.                 if cb.value():
  204.                     appendwindow(win)
  205.         else:
  206.             win='screen -t %s %s' % (title.value(), command.value())
  207.             commands.getoutput(win)
  208.             if cb.value():
  209.                 appendwindow(win)
  210.  
  211.     return 100
  212.  
  213. def appendwindow(win):
  214.     f=open(HOME+'/.screen-profiles/windows', 'a')
  215.     try:
  216.         f.write(win+"\n")
  217.  
  218.     except IOError:
  219.         return None
  220.  
  221.     finally:
  222.         f.close()
  223.  
  224. def readwindows():
  225.     f=open(HOME+'/.screen-profiles/windows', 'r')
  226.     try:
  227.         li=[]
  228.         for line in f.readlines():
  229.             if line.startswith("# "):
  230.                # this is a comment
  231.                window=[-1, line]
  232.             elif line.startswith("#"):
  233.                # this is an inactive window
  234.                window=[0, line.lstrip("#")]
  235.             else:
  236.                window=[1, line]
  237.             li.append(window)
  238.  
  239.         return li
  240.  
  241.     except IOError:
  242.         return None
  243.  
  244.     finally:
  245.         f.close()
  246.  
  247. def readstatus():
  248.     status={}
  249.     status["arch"]=0
  250.     status["battery"]=0
  251.     status["cpu-count"]=1
  252.     status["cpu-freq"]=1
  253.     status["ec2-cost"]=0
  254.     status["hostname"]=0
  255.     status["load-average"]=1
  256.     status["logo"]=1
  257.     status["mem-available"]=1
  258.     status["mem-used"]=1
  259.     status["menu"]=1
  260.     status["network-down"]=0
  261.     status["network-up"]=0
  262.     status["processes"]=0
  263.     status["reboot-required"]=1
  264.     status["release"]=1
  265.     status["users"]=0
  266.     status["updates-available"]=1
  267.     status["uptime"]=0
  268.     status["whoami"]=0
  269.     status["wifi-quality"]=0
  270.     if os.path.exists(HOME+'/.screen-profiles/status'):
  271.         f=open(HOME+'/.screen-profiles/status', 'r')
  272.         for line in f.readlines():
  273.            try:
  274.                line = line.rstrip()
  275.                (key, val) = line.split("=", 2)
  276.                if status.has_key(key) and (val == "1" or val == "0"):
  277.                    status[key] = val
  278.            except:
  279.                continue
  280.         f.close()
  281.     li=[]
  282.     keys = status.keys()
  283.     keys.sort()
  284.     for i in keys:
  285.         window=[int(status[i]), i]
  286.         li.append(window)
  287.     return li
  288.  
  289. def writestatus(items):
  290.     f=open(HOME+'/.screen-profiles/status', 'w')
  291.     try:
  292.         for i in items:
  293.             if i[0] == 1:
  294.                 f.write(i[1]+"=1\n")
  295.             elif i[0] == 0:
  296.                 f.write(i[1]+"=0\n")
  297.     except IOError:
  298.         return None
  299.     finally:
  300.         f.close()
  301.  
  302. def togglestatus(screen, size):
  303.     itemlist=readstatus()
  304.     rl=Label(_(""))
  305.     r=CheckboxTree(12, scroll=1)
  306.     count=0
  307.     for item in itemlist:
  308.        if item[0] != -1:
  309.             r.append(item[1],count,selected=item[0])
  310.        count=count+1
  311.     bb = ButtonBar(screen, ((_("Apply"), "apply"), (_("Cancel"), "cancel")), compact = 1)
  312.     g = GridForm(screen, _("Toggle status notifications:"), 2, 4 )
  313.     g.add(rl, 0, 0, anchorLeft=1, anchorTop=1, padding=(4,0,0,1))
  314.     g.add(r, 1, 0)
  315.     g.add(bb, 1, 1, padding=(4,1,0,0))
  316.     if bb.buttonPressed(g.runOnce()) != "cancel":
  317.         count=0
  318.         for item in itemlist:
  319.             if item[0] != -1:
  320.                 item[0] = r.getEntryValue(count)[1]
  321.             count=count+1
  322.         writestatus(itemlist)
  323.         button = messagebox(screen, 60, 4, _("Message"), _(RELOAD), \
  324.             buttons=((_("Menu"), )))
  325.     return 100
  326.  
  327. def writewindows(winlist):
  328.     f=open(HOME+'/.screen-profiles/windows', 'w')
  329.     try:
  330.         for win in winlist:
  331.             if win[0] == -1:
  332.                 f.write(win[1])
  333.             elif win[0] == 0:
  334.                 f.write("#"+win[1])
  335.             else:
  336.                 f.write(win[1])
  337.     except IOError:
  338.         return None
  339.     finally:
  340.         f.close()
  341.  
  342. def defaultwindows(screen, size):
  343.     winlist=readwindows()
  344.  
  345.     rl=Label(_("Windows:"))
  346.     r=CheckboxTree(10, scroll=1)
  347.     count=0
  348.     for win in winlist:
  349.        if win[0] != -1:
  350.             r.append(win[1],count,selected=win[0])
  351.        count=count+1
  352.  
  353.     bb = ButtonBar(screen, ((_("Apply"), "apply"), (_("Cancel"), "cancel")), compact = 1)
  354.  
  355.     g = GridForm(screen, _("Select window(s) to create by default:"), 2, 4 )
  356.     g.add(rl, 0, 0, anchorLeft=1, anchorTop=1, padding=(4,0,0,1))
  357.     g.add(r, 1, 0)
  358.     g.add(bb, 1, 1, padding=(4,1,0,0))
  359.  
  360.     if bb.buttonPressed(g.runOnce()) != "cancel":
  361.         count=0
  362.         for win in winlist:
  363.             if win[0] != -1:
  364.                 win[0] = r.getEntryValue(count)[1]
  365.             count=count+1
  366.  
  367.         writewindows(winlist)
  368.  
  369.     return 100
  370.  
  371. def install(screen, size, isInstalled):
  372.     if not isInstalled:
  373.         out = commands.getoutput("bash /usr/share/screen-profiles/screen-launcher-install")
  374.         if out == "":
  375.             out = _("Screen will be launched automatically next time you login.")
  376.  
  377.         button = messagebox(screen, 60, 2, "Message", out, \
  378.         buttons=((_("Menu"), )))
  379.         return 100
  380.     else:
  381.         out = commands.getoutput("bash /usr/share/screen-profiles/screen-launcher-uninstall")
  382.         if out == "":
  383.             out = _("Screen will not be used next time you login.")
  384.  
  385.         button = messagebox(screen, 60, 2, _("Message"), out, \
  386.         buttons=((_("Menu"), )))
  387.         return 101
  388.  
  389. def appendtofile(p, s):
  390.     f = open(p, 'a')
  391.     try:
  392.         f.write(s)
  393.     except IOError:
  394.         return
  395.     finally:
  396.         f.close()
  397.     return
  398.  
  399.  
  400. def getesckey():
  401.     path=HOME+'/.screen-profiles/keybindings'
  402.     if not os.path.exists(path):
  403.         return DEF_ESC
  404.     line = commands.getoutput("grep ^escape "+path)
  405.     if line == "":
  406.         return DEF_ESC
  407.     return line[line.find('^')+1]
  408.  
  409. def setesckey(key):
  410.     path = HOME+'/.screen-profiles/keybindings'
  411.     if key != "":
  412.         u = key[0].upper()
  413.         l = key[0].lower()
  414.         if not os.path.exists(path):
  415.             appendtofile(path, "escape ^"+u+l+"\nregister n ^"+l+"^c^"+l+"A\n")
  416.         else:
  417.             out = commands.getoutput("grep ^escape "+path)
  418.             if out == "":
  419.                appendtofile(path, "escape ^"+u+l+"\n")
  420.             else:
  421.                 out = commands.getoutput("sed -i -e 's/^escape \^.*/escape ^"+u+l+"/' "+path)
  422.             out = commands.getoutput("grep \"^register n \" "+path)
  423.             if out == "":
  424.                 appendtofile(path, "register n ^"+l+"^c^"+l+"A\n")
  425.             else:
  426.                 out = commands.getoutput("sed -i -e 's/^register n .*/register n ^"+l+"^c^"+l+"A/' "+path)
  427.  
  428. def chgesc(screen, size):
  429.     esc=Entry(2, text=getesckey(), returnExit=1)
  430.     escl=Label(_("Escape key: ctrl-"))
  431.     bb = ButtonBar(screen, ((_("Apply"), "apply"), (_("Cancel"), "cancel")), compact = 1)
  432.  
  433.     g = GridForm(screen, _("Change escape sequence:"), 2, 4 )
  434.     g.add(escl, 0, 0, anchorLeft=1, padding=(1,0,0,1))
  435.     g.add(esc, 1, 0, anchorLeft=1)
  436.     g.add(bb, 1, 1)
  437.     g.setTimer(100)
  438.     loop=1
  439.     while loop:
  440.         which=g.run()
  441.         if which == "TIMER":
  442.             val=esc.value()
  443.             if len(val) > 1:
  444.                 esc.set(val[1])
  445.             # Ensure that the escape sequence is not set to a number
  446.             try:
  447.                 dummy = int(esc.value())
  448.                 esc.set(DEF_ESC)
  449.             except:
  450.                # do nothing
  451.                dummy = "foo"
  452.         else:
  453.             loop=0
  454.     screen.popWindow()
  455.     if bb.buttonPressed(which) != "cancel":
  456.         setesckey(esc.value())
  457.         button = messagebox(screen, 60, 4, _("Message"), \
  458.             _(RELOAD), \
  459.             buttons=((_("Menu"), )))
  460.         if button == "exit":
  461.             return 0
  462.     return 100
  463.  
  464. def main():
  465.     """This is the main loop of our screen-profiles utility
  466.     """
  467.  
  468.     size = terminal_size()
  469.     screen = SnackScreen()
  470.     screen.drawRootText(1,0,_(' Screen Profiles Configuration Menu'))
  471.     screen.pushHelpLine(_('<Tab>/<Alt-Tab> between elements | <Return> Validates'))
  472.  
  473.     config = SafeConfigParser()
  474.  
  475.     isInstalled = (commands.getoutput('grep screen-launcher '+(HOME+'/.profile')) != "")
  476.  
  477.     tag = 100
  478.  
  479.     while tag > 0 :
  480.         tag = menu(screen, size, isInstalled)
  481.         if tag == 1:
  482.             tag = help(screen, size, config)
  483.         elif tag == 2:
  484.             tag = profile(screen, size)
  485.         elif tag == 3:
  486.             tag = togglestatus(screen, size)
  487.         elif tag == 4:
  488.             tag = keybindings(screen, size)
  489.     elif tag == 5:
  490.             tag = chgesc(screen, size)
  491.         elif tag == 6:
  492.             tag = newwindow(screen, size)
  493.         elif tag == 7:
  494.             tag = defaultwindows(screen, size)
  495.         elif tag == 8:
  496.             tag = install(screen, size, isInstalled)
  497.             isInstalled=(tag == 100)
  498.  
  499.     screen.finish()
  500.     sys.exit(0)
  501.  
  502.  
  503. if __name__ == "__main__": main()
  504.